<template>
    <div class="app-container">
        <div class="add-row-center-box" style="width: 960px">
            <el-form ref="form" :model="form" inline :rules="rules" label-position="top"
                     class="form-item-column column-2">
                <el-form-item label="任务类型" prop="taskCategory">
                    <el-select v-model="form.taskCategory" size="small" placeholder="请选择任务类型" filterable clearable
                               @change="onCategoryChange">
                        <el-option v-for="item in dict.type.mos_task_type" :value="item.value" :label="item.label"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="计划完成时间" prop="finishTime">
                    <el-date-picker v-model="form.finishTime" type="date" size="small" placeholder="选择完成时间"
                                    value-format="yyyy-MM-dd" style="width: 100%"/>
                </el-form-item>
                <el-form-item label="关联合同" prop="contractId">
                    <el-select v-model="newContractId" size="small" placeholder="请选择关联合同" filterable clearable
                               @change="onCategoryChange1">
                        <el-option v-for="item in contractData" :value="item" :label="item.contractName"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否需要彩绘" prop="isPainting">
                    <el-select v-model="isPaintingName" size="small" placeholder="请选择关联合同" filterable clearable
                               @change="onCategoryChange2">
                        <el-option v-for="item in isPaintingData" :value="item.value" :label="item.name"/>
                    </el-select>
                </el-form-item>

                <!--增行表格-->
                <div class="form-table">
                    <el-form-item label="生产目标" prop="productVoList" style="width: 100%">
                        <label slot="label" class="el-form-item__label">生产目标
                            <el-button type="text" size="mini" icon="el-icon-plus" @click="onAddRow">增行</el-button>
                        </label>
                        <el-table :data="form.productVoList" v-loading="tableLoading">
                            <el-table-column label="*物料编号" prop="productNo">
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.productNo"
                                              :prop="'productVoList.'+$index+'.productNo'">
                                    <el-input v-model="row.productNo" size="mini" placeholder="请输入物料编号"
                                              @keyup.enter.native="(e) => checkProduceTarget(row, $index)"
                                              @blur="(e) => checkProduceTarget(row)"/>
                                </el-form-item>
                            </el-table-column>
                            <el-table-column label="物料名称" prop="productName">
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.productName"
                                              :prop="'productVoList.'+$index+'.productName'">
                                    <el-input v-model="row.productName" size="mini" placeholder="请输入物料名称"
                                              @keyup.enter.native="(e) => checkProduceTargetName(row, $index)"
                                              @blur="(e) => checkProduceTargetName(row)"/>
                                </el-form-item>
                            </el-table-column>
                            <el-table-column label="客户" prop="productCustomer"/>
                            <el-table-column label="规格" prop="productSku">productSku
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.productSku"
                                              :prop="'productVoList.'+$index+'.productSku'">
                                    <el-input v-model="row.productSku" size="mini" placeholder="请输入规格"/>
                                </el-form-item>
                               </el-table-column>
                            <el-table-column label="颜色" prop="productColour">
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.productColour"
                                              :prop="'productVoList.'+$index+'.productColour'">
                                    <el-input v-model="row.productColour" size="mini" placeholder="请输入颜色"/>
                                </el-form-item>
                               </el-table-column>
                            <el-table-column label="*数量" prop="productNum">
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.productNum"
                                              :prop="'productVoList.'+$index+'.productNum'">
                                    <el-input v-model.number="row.productNum" size="mini" placeholder="请输入数量"
                                              :disabled="!row.productName"/>
                                </el-form-item>
                            </el-table-column>
                            <el-table-column width="50" class-name="small-padding">
                                <el-button slot-scope="{row, $index}" size="mini" type="text"
                                           @click="onDeleteNeed($index)">
                                    删除
                                </el-button>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </div>
            </el-form>

            <div class="footer">
                <el-button size="small" @click="cancel">取 消</el-button>
                <el-button type="primary" size="small" @click="submitForm">确 定</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import {handleEnum, responseEnum, taskTypeEnum} from "../../../const/const";
import ImageUpload from "@/components/ImageUpload/"
import {INTEGER, IS_INTEGER} from "../../../utils/validate";
import {addTask, getProductByNo, getContractList,getProductByName} from "./api";
import _ from "lodash";
import {getProductInfo} from "../../material/list/api";

export default {
    name: 'taskAdd',
    dicts: ['mos_task_type'],
    components: {ImageUpload},
    data() {
        return {
            isPaintingName:'是',
             loading: false,
            contractData:[],
            newContractId:'',
            isPaintingData:[{
                value:1,
                name:'是'
            },
            {
                value:0,
                name:'否'
            }],
            // 操作枚举
            handleEnum,
            IS_INTEGER,
            // 表格loading
            tableLoading: false,
            form: {
                isPainting:'1',//是否彩绘
                taskCategory: null,  // 产品类型id
                contractId:null,//关联合同
                contractNo:null,//关联合同编号
                contractName:null,//关联合同名称
                finishTime: null, // 计划完成时间
                productVoList: [{ // 生产目标
                    productName: null, // 物料名称
                    productNo: null, // 物料编号
                    productCustomer: null, // 客户
                    productColour: null, // 颜色
                    productNum: null // 数量
                }]
            },
            // 校验
            rules: {
                productName:[{required: true, message: '请输入物料名称'}],
                 productColour:[{required: true, message: '请输入物料颜色'}],
                 productSku:[{required: false, message: '请输入物料规格'}],
                taskCategory: [{required: true, message: '请选择产品类型'}],
                contractId:[{required: false, message: '请选择关联合同'}],
                finishTime: [{required: true, message: '请选择完成时间'}],
                productVoList: [{required: true, message: '请填写生产目标'}],
                productNo: [{required: true, message: '请输入物料编号'}],
                productNum: [{required: true, pattern: IS_INTEGER, message: '请输入正整数'}]
            },

            // 存起输入框的值，避免重复查询
            tempInput: null,

            currentRow: ''
        }
    },
    created() {
        this.getContractList()
    },
    methods: {
        getContractList(){
              this.loading = true
              getContractList({}).then(res => {
                  if (res.code === responseEnum.success) {
                      this.contractData=res.data
                  } else {
                      // this.$message.error(res.msg);
                  }
              }).finally(() => this.loading = false)


        },
        onCategoryChange1(val){
            this.form.contractId=val.id
            this.newContractId=val.contractName
            this.form.contractName=val.contractName
            this.$forceUpdate()
        },
        onCategoryChange2(val){
            this.form.isPainting=val
            if(val==1){
                this.isPaintingName='是'
            }else{
                 this.isPaintingName='否'
            }
        },
        /**
         * 切换任务类型
         */
        onCategoryChange(val) {
            if (this.currentRow) {
                this.checkProduceTarget(this.currentRow);
            }
        },
        /**
         * 通过产品名称查询生产目标信息
         */
        checkProduceTargetName(row) {
            this.currentRow = row;
            // if (!row.productNo || this.tempInput === row.productNo) {
            //     return;
            // }
            if (!this.form.taskCategory) {
                this.$message.error('请先选择任务类型');
                this.$refs.form.validateField('taskCategory');
                return;
            }
            // 成品为1，其他半成品均为2
            // const val = this.form.taskCategory === taskTypeEnum.production ? taskTypeEnum.production : taskTypeEnum.half;
            const val = this.form.taskCategory
            this.tableLoading = true;
            getProductByName(row.productName, val).then(res => {
                if (res.code === responseEnum.success && res.data) {
                      row.productNo = res.data.productNo;
                    row.productName = res.data.productName;
                    row.productCustomer = res.data.productCustomer;
                    row.productColour = res.data.productColour;
                    row.productSku = res.data.productSku;
                    row.productNum = res.data.productStock;
                    row.productId = res.data.productId;
                }else{
                    this.resetRow(row);
                    this.$message.error("请输入正确的物料信息");
                    }
            }).catch((e) => this.resetRow(row)).finally(() => this.tableLoading = false)
        },
        /**
         * 通过产品编号查询生产目标信息
         */
        checkProduceTarget(row) {
            this.currentRow = row;
            // if (!row.productNo || this.tempInput === row.productNo) {
            //     return;
            // }
            if (!this.form.taskCategory) {
                this.$message.error('请先选择任务类型');
                this.$refs.form.validateField('taskCategory');
                return;
            }
            // 成品为1，其他半成品均为2
            // const val = this.form.taskCategory === taskTypeEnum.production ? taskTypeEnum.production : taskTypeEnum.half;
            const val = this.form.taskCategory
            this.tempInput = row.productNo;
            this.tableLoading = true;
            getProductByNo(row.productNo, val).then(res => {
                if (res.code === responseEnum.success && res.data) {
                    row.productName = res.data.productName;
                    row.productCustomer = res.data.productCustomer;
                    row.productColour = res.data.productColour;
                    row.productSku = res.data.productSku;
                    row.productNum = res.data.productStock;
                    row.productId = res.data.productId;
                }else{
                    this.resetRow(row);
                    this.$message.error("请输入正确的物料信息");
                    }
            }).catch((e) => this.resetRow(row)).finally(() => this.tableLoading = false)
        },
        /**
         * 重置行
         */
        resetRow(row) {
            row.productName = '';
            row.productCustomer = '';
            row.productColour = '';
            row.productSku = '';
            row.productNum = '';
            row.productId = null;
            this.$nextTick(() => {
                this.$refs.form.clearValidate();
            })
        },
        /**
         * 增行
         */
        onAddRow() {
            const row = _.cloneDeep(this.$options.data().form.productVoList[0]);
            this.form.productVoList.push(row);
        },
        /**
         * 删除行
         */
        onDeleteNeed(index) {
            this.form.productVoList.splice(index, 1)
        },
        /**
         * 提交表单
         */
        submitForm() {
            if (this.form.productVoList.some(item => !item.productName)) {
                this.$message.error('请添加生产目标！');
                return;
            }
            for (var i = 0; i < this.form.productVoList.length; i++) {
                if(this.form.productVoList[i].productNum<=0){
                    this.$message.error('生产目标数量必须大于0');
                    return;
                }
            }
            this.$refs.form.validate(valid => {
                if (valid) {
                    const loading = this.$loading({lock: true});
                    addTask(this.form).then(res => {
                        if (res.code === responseEnum.success) {
                            this.$message.success('任务新建成功');
                            this.$tab.closeOpenPage();
                            this.$router.replace({path: '/produce/produce/task'});
                        } else {
                      this.$modal.msgError(res);
                        }
                    }).finally(() => loading.close())
                }
            })
        },
        /*取消、关闭*/
        cancel() {
            this.$tab.closeOpenPage();
            this.$router.back()
        }
    }
}
</script>

<style lang="scss" scoped>
.form-table {
    margin-top: 20px;

    ::v-deep.el-form-item__content {
        line-height: unset;
    }
}
</style>
